# -*- mode: snippet -*-
# name: shiny renderCachedPlot
# key: shiny.renderCachedPlot
# contributor: Shuguang Sun
# --
library(shiny)
ui <- function(){
  tagList(
    ## We select a data.frame to plot
    selectInput(
      "tbl",
      "Table",
      c("iris", "mtcars", "airquality")
    ),
    ## This plotOutput will be cached
    plotOutput("plot")
  )
}

server <- function(
  input,
  output,
  session
){

  ## The cache mechanism is made available by renderCachedPlot
  output$plot <- renderCachedPlot({
    ## Plotting the selected data.frame
    plot(get(input$tbl))
  }, cacheKeyExpr = {
    ## List here all the reactive expression that will
    ## be used as cache key when running the app,
    ## you will see that the first time you plot one
    ## graph, it takes a couple of seconds,
    ## but the second time, it's almost
    ## instantaneous
    input$tbl
  })

}

shinyApp(ui, server)